//
//  ApplyInabilityViewController.swift
//  LongTermInsurance
//
//  Created by zolobdz on 2018/11/28.
//  Copyright © 2018年 HeChao. All rights reserved.
//

import UIKit
import SnapKit
import ObjectMapper

class ApplyInabilityViewController: UIViewController {
    lazy var saveButton: UIButton = {
        let button = UIButton()
        button.setTitle("保  存", for: .normal)
        button.backgroundColor = CDColor.themePink
        return button
    }()
    
    lazy var questionView: QuestionView = {
        let view = QuestionView()
        view.tz_width = screenWidth
        return view
    }()
    
    lazy var fileChooseView: InabilityChooseView = {
        let view = R.nib.inabilityChooseView().instantiate(withOwner: nil, options: nil).first as! InabilityChooseView
        return view
    }()
    
    lazy var dataSource: [QuestionModel] = {
        
        let path = CDArchiverPath.inabilityStateFilePath
        if FileManager.default.fileExists(atPath: path) {
            
            if let dict = NSDictionary(contentsOfFile: path) {
                if let array = dict["inability"] as? [[String: Any]]{
                    let array = Mapper<QuestionModel>().mapArray(JSONArray: array)
                    return array
                }
            }
        }
        
        let plistPath = Bundle.main.url(forResource: "apply_inability", withExtension: "plist")!
        let dataDict = NSArray(contentsOf: plistPath) as! [[String: Any]]
        let array = Mapper<QuestionModel>().mapArray(JSONArray: dataDict)
        return array
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "失能相关信息"
        view.backgroundColor = CDColor.grayBackgroundColorA
        view.addSubview(questionView)
        view.addSubview(saveButton)
        
        questionView.snp.remakeConstraints { (make) in
            make.top.right.left.equalTo(0)
            make.bottom.equalTo(saveButton.snp.top).offset(-20)
        }
        questionView.tableView.tableFooterView = fileChooseView
        
        saveButton.snp.remakeConstraints { (make) in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            if #available(iOS 11.0, *) {
                make.bottom.equalTo(-(view.safeAreaInsets.bottom + 50))
            } else {
                make.bottom.equalTo(-50)
                // Fallback on earlier versions
            }
            make.height.equalTo(30.0)
        }
        
        saveButton.addTarget(self, action: #selector(saveButtonAction), for: UIControlEvents.touchUpInside)
        
        
        questionView.dataSource = dataSource
        questionView.tableView.reloadData()
    }
    
    @objc func saveButtonAction() {
        for (index,model) in dataSource.enumerated() {
            if index == 0 && !model.items.isEmpty {
                if model.selectedIndex.count == 0 || (model.selectedIndex.count == 1 && model.selectedIndex.first! == IndexNone) {
                    makeToast("请填写-\(model.questionTitle)")
                    return
                }
            }
            
            if index == 1 {
                if model.enterDetail.count == 0 {
                    makeToast("请填写-\(model.questionTitle)")
                    return
                }
            }
        }
        
        if fileChooseView.chooseORGModel == nil && fileChooseView.chooseHomeModel == nil {
            makeToast("请选择-服务方式")
            return
        }
        
        if fileChooseView.chooseZoneModel == nil {
            makeToast("请选择-乡镇区划")
            return
        }
        if fileChooseView.chooseStreetModel == nil{
            makeToast("请选择-街道区划")
            return
        }
        
        
        let path = CDArchiverPath.inabilityStateFilePath
        let json = dataSource.toJSON()
        
        let dict = NSMutableDictionary()
        dict.setValue(json, forKey: "inability")
        let success = dict.write(toFile: path, atomically: false)

        // photo

        if let data = UserDefaults.standard.array(forKey: CDUserDefaultKey.userUploadPhotos) as? [[String: Any]]{
            let array = Mapper<ApplyPhotoModel>().mapArray(JSONArray: data)
            
            CDUtility.showHud()
            var index = 0
            var done = false
            var networking = false
            let queue = DispatchQueue(label: "com.brycegao.gcdtest")
            queue.async {
                while(!done) {
                    if networking {
                        debugPrint("networking...index:\(index)")
                        continue
                    }
                    debugPrint("working...index:\(index)")
                    if index >= array.count {
                        debugPrint("OKOK!!...index:\(index)")
                        done = true
                        break
                    }
                    let model = array[index]
                    if model.uploaded {
                        index += 1
                        continue
                    }
                    guard let imgData = model.data else {
                        index += 1
                        continue
                    }
                    
                    networking = true
                    let bytes = imgData.base64EncodedString()
                    let paramString = "<FileName>\(model.name)</FileName><bite>\(bytes)</bite>"//"<json>"+"<>"+"</json>"
                    debugPrint(array.first!.name)
                    NetworkingHandle.fetchNetworkData(method: "upLoadFile", paramString: paramString, success: { (dict) in
                        model.uploaded = true
                        index += 1
                        networking = false
                        debugPrint("Successed!!...index:\(index)")
                        if let code = dict["ResultCode"] as? Int,code == 0 {
                            return
                        }
                        if let code = dict["ResultCode"] as? Int,code == 1 {
                            if let msgString = dict["ResultMessage"] as? String {
                                CDUtility.showMSG(message: msgString)
                            }
                        }
                    }) {
                        index += 1
                        networking = false
                        debugPrint("Failed!!...index:\(index)")
                        print("")
                    }
                }
                DispatchQueue.main.async {
                    CDUtility.hidHud()
                    
                    let jsonArray = array.compactMap { model -> NSDictionary? in
                        return [
                            "name": model.name,
                            "data": model.data ?? Data(),
                            "isRemote": model.isRemote,
                            "uploaded": model.uploaded
                        ]
                    }
                    UserDefaults.standard.set(jsonArray, forKey: CDUserDefaultKey.userUploadPhotos)
                    CDUtility.showMSG(message: "提交成功！")
                    self.navigationController?.popViewController(animated: true)
                }
            }
            
            
        } else {
            if success {
                makeToast("保存成功")
                navigationController?.popViewController(animated: true)
            } else {
                makeToast("保存失败")
            }
        }


    }
    
}
